
package com.lagou.service.impl;

import com.lagou.api.ICodeService;
import com.lagou.api.IEmailService;
import com.lagou.api.IUserService;
import com.lagou.dao.AuthCodeDao;
import com.lagou.pojo.AuthCode;
import org.apache.commons.lang.StringUtils;
import org.apache.dubbo.config.annotation.Reference;
import org.apache.dubbo.config.annotation.Service;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;

import java.util.Date;

/**
 * Created by wangq on 2021/9/26.
 */
@Service
public class CodeServiceImpl implements ICodeService {
    private static final Logger logger = LoggerFactory.getLogger(CodeServiceImpl.class);

    private static final int RIGHT = 0; // 验证码正确

    private static final int ERROR = 1; // 验证码错误

    private static final int TIMEOUT = 2; // 验证码超时

    @Autowired
    AuthCodeDao authCodeDao;

//    @Autowired
//    EmailFeignClient emailFeignClient;

//    @Autowired
//    UserFeignClient userFeignClient;

    @Reference
    IUserService iUserService;

    @Reference
    IEmailService iEmailService;

    @Override
    public Boolean create(String email) {
        if (iUserService.isRegistered(email)) {
            return false;
        }
        // 生成6位随机验证码
        String authCodeStr = randomCode();

        // 保存验证码信息到数据库
        AuthCode authCode = new AuthCode(email, authCodeStr);
        authCodeDao.save(authCode);

        // 调用邮件服务feign发送验证码到邮箱
        Boolean sendStatus = iEmailService.send(email, authCodeStr);
        if (sendStatus) {
            logger.info("验证码：{}已发送到邮箱{}", authCodeStr, email);
        }
        return sendStatus;
    }

    private String randomCode() {
        // 生成大于0小于1的double类型随机数
        double random = Math.random();
        // 随机数*9后再+1，保证整数位不为0，再*100000，小数点右移5位后，保证取整时，整数位是6位
        int authCode = (int) ((random * 9 + 1) * 100000);
        return String.valueOf(authCode);
    }

    @Override
    public Integer validate(String email, String code) {
        AuthCode authCode = authCodeDao.findFirstByEmailOrderByCreatetimeDesc(email);
        if (authCode == null) {
            return ERROR;
        }
        if (!StringUtils.equals(authCode.getCode(), code)) {
            return ERROR;
        }
        if (new Date().after(authCode.getExpiretime())) {
            return TIMEOUT;
        }
        return RIGHT;
    }

}